package com.sicheng.metadata.juc.线程通信.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/2/2 21:07
 */
public class PrintNumber {
    private int target = 1;
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition[] conditions = new Condition[3];


    public PrintNumber() {
    }

    static {
        for (int i = 0; i < conditions.length; i++) {
            conditions[i] = lock.newCondition();
        }
    }

    public void printNumber(int number) {
        lock.lock();
        try {
            while (target != number) {
                conditions[number - 1].await();
            }

            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + "--->" + number);
            target++;
            if (target > 3)
                target = 1;

            conditions[target - 1].signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
